import 'package:flutter/material.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:io';

///存储录音的信息
class Recording {
  final String filePath;
  final Duration duration;
  Recording({required this.duration, required this.filePath});
}

class RecordingProvider with ChangeNotifier {
  FlutterSoundRecorder? _recorder; //录音控制器
  FlutterSoundPlayer? _player; //播放控制器
  final AudioPlayer _audioPlayer = AudioPlayer(); //用来获取时长的控制器
  bool _isRecording = false; //开始录音
  bool _isPlaying = false; //开始播放
  String? _filePath; //文件路径
  Duration? _recordingDuration; //播放时长
  int index = 0;
  int _fileCount = 0; //文件数量
  List<Recording> _recordings = []; //录音列表
  bool _recorderInitialized = false; //是否初始化
  bool _playerInitialized = false; //是否初始化
  List<Recording> get recordings => _recordings;
  bool get isRecording => _isRecording;
  int get fileCount => _fileCount;
  bool get isPlaying => _isPlaying;
  Duration? get recordingDuration => _recordingDuration;
  RecordingProvider() {
    _recorder = FlutterSoundRecorder();
    _player = FlutterSoundPlayer();
    _initializeRecorder();
  }
  Future<void> _initializeRecorder() async {
    if (_recorderInitialized && _playerInitialized) {
      return;
    }

    try {
      var status = await Permission.microphone.request();
      if (status != PermissionStatus.granted) {
        throw RecordingPermissionException('Microphone permission not granted');
      }

      if (!_recorderInitialized) {
        await _recorder!.openRecorder();
        _recorderInitialized = true;
      }

      if (!_playerInitialized) {
        await _player!.openPlayer();
        _player!.setSubscriptionDuration(Duration(milliseconds: 10));
        _player!.onProgress!.listen((e) {
          if (e != null && e.position == e.duration) {
            _stopPlaybackAutomatically();
          }
        });
        _playerInitialized = true;
      }
    } catch (e) {
      print('Failed to initialize recorder/player: $e');
    }
  }

  ///请求权限
  Future<bool> requestMicrophonePermission(BuildContext context) async {
    var status = await Permission.microphone.request();
    if (status != PermissionStatus.granted) {
      if (status == PermissionStatus.denied) {
        _showPermissionDeniedDialog(context);
      } else if (status == PermissionStatus.permanentlyDenied) {
        _showPermissionPermanentlyDeniedDialog(context);
      }
      return false;
    }
    return true;
  }

  Future<String> getFilePath() async {
    Directory tempDir = await getTemporaryDirectory();
    String tempPath =
        '${tempDir.path}/audio_example_${DateTime.now().millisecondsSinceEpoch}.aac';
    return tempPath;
  }

  ///开始录音
  Future<void> startRecording(BuildContext context) async {
    if (await requestMicrophonePermission(context)) {
      try {
        await _initializeRecorder();
        _filePath = await getFilePath();
        await _recorder!.startRecorder(
          toFile: _filePath,
          codec: Codec.aacADTS,
        );
        notifyListeners();
        _isRecording = true;
      } catch (e) {
        print('Failed to start recording: $e');
      }
    }
  }

  Future<void> stopRecording() async {
    try {
      await _recorder!.stopRecorder();

      _isRecording = false;
      notifyListeners();
      await getRecordingDuration();
      if (_filePath != null && _recordingDuration != null) {
        _recordings.add(
            Recording(duration: _recordingDuration!, filePath: _filePath!));
      }

      // await getFileCountInTempDir();
      await _updateFileCount();
      print('Recording saved to: $_filePath');
    } catch (e) {
      print('Failed to stop recording: $e');
    }
  }

  Future<void> getRecordingDuration() async {
    if (_filePath != null) {
      try {
        await _audioPlayer.setSourceUrl(_filePath!);
        print(_filePath);
        _recordingDuration = await _audioPlayer.getDuration();
        notifyListeners();
        print('Recording duration: $_recordingDuration');
      } catch (e) {
        print('Failed to get recording duration: $e');
      }
    }
  }

  ///开始播放
  Future<void> startPlayback(String filePath) async {
    try {
      await _player!.startPlayer(
        fromURI: filePath,
        codec: Codec.aacADTS,
      );
      _isPlaying = true;
      notifyListeners();
    } catch (e) {
      print('Failed to start playback: $e');
    }
  }

  Future<void> stopPlayback() async {
    try {
      await _player!.stopPlayer();
      _isPlaying = false;
      notifyListeners();
    } catch (e) {
      print('Failed to stop playback: $e');
    }
  }

  void _stopPlaybackAutomatically() {
    _isPlaying = false;
    print('object');
    notifyListeners();
  }

  Future<void> clearTemporaryDirectory() async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      if (tempDir.existsSync()) {
        tempDir.deleteSync(recursive: true);
      }
      _recordings.clear();
      // await getFileCountInTempDir();
      await _updateFileCount();
      notifyListeners();
      print('Temporary directory cleared');
    } catch (e) {
      print('Failed to clear temporary directory: $e');
    }
  }

  // Future<int> getFileCountInTempDir() async {
  //   try {
  //     Directory tempdir = await getTemporaryDirectory();
  //     if (tempdir.existsSync()) {
  //       List<FileSystemEntity> files = tempdir.listSync();
  //       int fileCount = files.where((file) => file is File).length;
  //       return fileCount;
  //     }
  //   } catch (e) {
  //     print('Failed to get file count in temporary directory: $e');
  //   }
  //   return 0;
  // }

  Future<void> _updateFileCount() async {
    try {
      Directory tempdir = await getTemporaryDirectory();
      if (tempdir.existsSync()) {
        List<FileSystemEntity> files = tempdir.listSync();
        _fileCount = files.where((file) => file is File).length;
        notifyListeners();
      }
    } catch (e) {
      print('Failed to get file count in temporary directory: $e');
    }
  }

  void dispose() {
    _closeAudioSessions();
    super.dispose();
  }

  Future<void> _closeAudioSessions() async {
    try {
      if (_isPlaying) {
        await _player!.stopPlayer();
      }
      await _player!.closePlayer();
    } catch (e) {
      print('Failed to close player: $e');
    }
    try {
      await _recorder!.closeRecorder();
    } catch (e) {
      print('Failed to close recorder: $e');
    }
    await _audioPlayer.dispose();
    await clearTemporaryDirectory();
  }

  void _showPermissionDeniedDialog(BuildContext context) {
    // 显示一个对话框，告知用户权限被拒绝
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('权限被拒绝'),
        content: Text('录音功能需要麦克风权限，请在设置中授予权限。'),
        actions: <Widget>[
          TextButton(
            child: Text('取消'),
            onPressed: () => Navigator.of(context).pop(),
          ),
          TextButton(
            child: Text('去设置'),
            onPressed: () {
              openAppSettings();
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
    );
  }

  void _showPermissionPermanentlyDeniedDialog(BuildContext context) {
    // 显示一个对话框，告知用户权限被永久拒绝
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('权限被永久拒绝'),
        content: Text('录音功能需要麦克风权限，请在设置中手动授予权限。'),
        actions: <Widget>[
          TextButton(
            child: Text('取消'),
            onPressed: () => Navigator.of(context).pop(),
          ),
          TextButton(
            child: Text('去设置'),
            onPressed: () {
              openAppSettings();
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
    );
  }
}
